import { env } from "../config";
import { ApiCall, TsrpcErrorType } from "tsrpc";
import pop_component from "../component/pop_component";
import UserManager from "../core/manage/UserManager";
import { ReqCheck, ResCheck } from "../shared/api_backend/PtlCheck";
import sdk from '../core/index';
import { ClientManage } from '../core/index';
import { ComType } from "../core/tool/component";
import { mathType } from "../core/tool/face";

export default async function (call: ApiCall<ReqCheck, ResCheck>) {
    let account = call.req.account;
  
    let player = UserManager.getOnlinePlayer(account);
    if(!player && env.DEV){
        player = await UserManager.loadPlayerFromDB(account)
        if(!player){
            call.error({
                message: '不存在的账号,请先注册',
                type: TsrpcErrorType.ApiError,
            });
            return;
        }
        account = player.id;
    }
    if (!player) {
        call.error({
            message: '角色目前不在线哦,请和@机器人 互动一次',
            type: TsrpcErrorType.ApiError,
        });
        return;
    }
    let token = sdk.tool.common.uuid;
    ClientManage.waitTokenMap.set(token, { id: account, expiredTime: Date.now() + 30 * 60 * 1000 });
    let com = player.getComponent(ComType.对话框) as pop_component;

    let card = sdk.tool.card.create();
    card.title('检查授权')
    card.l('你的账号正在网页请求检查授权')
    
    // 配置化按钮意图 - mathType包含在配置中
    const buttonConfigs: any[] = [
        {
            text: '授权',
            mathType: mathType.完全匹配,
            action: () => {
                com.close();
                if (player) {
                    player.client_text('检查授权成功');
                    ClientManage.passToken(token);
                }
            }
        },
        {
            text: '取消',
            mathType: mathType.完全匹配,
            action: () => {
                com.close();
                if (player) {
                    player.client_text('取消检查授权');
                    ClientManage.waitTokenMap.delete(token);
                }
            }
        }
    ];
    // 使用pop_component的封装方法
    com.registerPopupButtonIntents(buttonConfigs, player,card);
    
    com._content = card.getText();
    com.reg(mathType.全部拦截,'',()=>{
        com.active();
    },player)
    com.active();

    if(env.DEV){
        ClientManage.passToken(token);
    }
    call.succ({
        token: token
    })
}